import { useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less";
import HomePage_ChartLineComponent from "../chartLine";
import { $beforeunload, $echartsData, $eventBus, $EventBus_off, $EventBus_on, $nanoid_uuid, $websocketUrl, $switch_index, $switch_mode, $switch_tagName } from "../../../../common/utils";
import HomePage_AnalysisComponent_ChartLinesComponent from "./component/chartLines";
import HomePage_AnalysisComponent_ViewDimensionsComponent from "./component/viewDimensions";
import HomePage_AnalysisComponent_DataStaticComponent from "./component/dataStatic";
import { modeType } from "../../../../common/interface";
import ReconnectingWebSocket from 'reconnecting-websocket';
import { message } from "antd";
import { useNavigate } from "react-router-dom";
import { $Http } from "../../../../network";
import HomePage_AnalysisComponent_CorrelationComponent from "./component/correlation";

// 主页-分析组件
interface homePageAnalysisComponentInterface {
    isTag?: boolean
    monitoringType?: string
    monitorModalName?: string
    mode?: modeType
    tableName?: string
}
const HomePage_AnalysisComponent: React.FC<homePageAnalysisComponentInterface> = (props) => {

    const navigate = useNavigate()
    let [sourceData, setSourceData] = useState<object>({})
    let [paramsData, setParamsData] = useState<object>({})
    const uuid = useRef<string>("")
    const socket = useRef<any>(null)
    const viewDimensionsComponentRef = useRef<HTMLDivElement>(null);
    const [showTypeIdx, setShowTypeIdx] = useState<number>(0)
    const [isWarningLine, setIsWarningLine] = useState<boolean>(false)
    const [zoomList, setZoomList] = useState<Array<number>>([0, 100])
    const [viewDimensionsComponentHeight, setViewDimensionsComponentHeight] = useState<number>(0)
    const resize_observer = () => {
        const observer = new ResizeObserver((list) => {
            list.forEach((item) => {
                item["target"] === viewDimensionsComponentRef.current && setViewDimensionsComponentHeight(item.contentRect.height)
            })
        })
        viewDimensionsComponentRef.current && observer.observe(viewDimensionsComponentRef.current)
    }

    // 广播函数数据
    const eventBusFuncData = {
        switchIdx: (data: object) => {
            setShowTypeIdx(data["data"]["switchIdx"])
        },
        headerOperationHistory: (data: object) => {
            navigate("/home/statisticalQuery/curveAnalysis", { state: { tagName: props.mode === "multiple" ? `多${props.monitoringType}同指标` : `单${props.monitoringType}多指标` } })
        },
        isWarningLine: (data: object) => {
            setIsWarningLine(data["data"]["isWarningLine"])
        }
    }

    const ws_connect = () => {
        uuid.current = $nanoid_uuid()
        socket.current = new ReconnectingWebSocket($websocketUrl)
        socket.current.onopen = (data: object) => {
            socket.current.send(JSON.stringify(
                {
                    token: sessionStorage.bearerToken,
                    uuid: uuid.current,
                    module: "chart",
                    type: "send",
                    mode: props.mode,
                    time: paramsData["time"],
                    index: paramsData["index"],
                    deviceID: paramsData["deviceIDList"],
                }
            ))
            setParamsData({ ...paramsData })
        }
        socket.current.onmessage = (data: object) => {
            data = JSON.parse(data["data"])
            if (data["status"] === 200) {
                sourceData = data
            }

            else {
                sourceData = {}
                message.error(data["error"])
                if (data["status"] === 401) {
                    navigate("login"); //刷新 见 HomePage 
                }
            }
            setSourceData({ ...sourceData })
        }
        $beforeunload(socket.current, uuid.current, "chart")
    }
    const ws_close = () => {
        socket.current.send(JSON.stringify(
            {
                uuid: uuid.current,
                module: "chart",
                time: paramsData["time"],
                type: "close"
            }
        ))
    }

    const change_paramsData = (data: object) => {
        paramsData = { ...data }

        setParamsData({ ...paramsData })
        if (props.mode) {
            uuid.current && socket.current ? socket.current.send(JSON.stringify(
                {
                    token: sessionStorage.bearerToken,
                    uuid: uuid.current,
                    module: "chart",
                    type: "send",
                    mode: props.mode,
                    time: paramsData["time"],
                    index: paramsData["index"],
                    deviceID: paramsData["deviceIDList"],
                }
            )) : ws_connect()
        }
        else {
            const tempParamsData = { ...paramsData }
            tempParamsData["id"] = tempParamsData["deviceIDList"]
            delete tempParamsData["mode"]
            delete tempParamsData["tableName"]
            delete tempParamsData["monitoringType"]
            delete tempParamsData["deviceIDList"]
            delete tempParamsData["deviceList"]
            delete tempParamsData["deviceOtherList"]
            $Http("search", {
                typeName: "统计查询/曲线分析",
                ...tempParamsData

            }).then((res) => {
                setSourceData({ ...res["data"] })
            })
        }
    }

    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        resize_observer()
        return () => {
            $EventBus_off(eventBusFuncData)
            !props.isTag && ws_close()
        }
    }, [])

    return (
        <div className={lessModule["homePageAnalysisComponent"]}>
            <div className={lessModule["homePageAnalysisComponent-left"]}>
                {
                    paramsData["deviceList"]?.length > 0 && Object.keys(sourceData).length > 0 && <>
                        {
                            !showTypeIdx && <div className={lessModule["homePageAnalysisComponent-left__group"]}>
                                {
                                    props.mode === "multiple" || !paramsData["tagName"].includes("多指标") && <div className={`${lessModule["left-group__index"]} ${lessModule["left-group__chartLinesIndex"]}`}>{$switch_index(paramsData["index"]?.[0])}</div>
                                }
                                <div className={lessModule["left-group__chart"]}>
                                    <HomePage_AnalysisComponent_ChartLinesComponent isWarningLine={isWarningLine} mode={props.mode} paramsData={paramsData} sourceData={sourceData} />
                                </div>
                            </div>
                        }
                        {
                            showTypeIdx === 1 && (props.mode ? paramsData[$switch_mode(props.mode, "deviceList", "index")] : $switch_tagName(paramsData["tagName"], paramsData["deviceList"], paramsData["index"], ["A", "B"])).concat(["zoomAxis"]).map((item, idx) => {
                                return (
                                    <div key={`chartListItem${idx}`} className={lessModule["homePageAnalysisComponent-left__group"]}
                                        style={{
                                            height: item === "zoomAxis" ? $echartsData["zoomAxisHeight"] : `calc((100% - ${$echartsData["zoomAxisHeight"]}px) / ${props.mode ? paramsData[$switch_mode(props.mode, "deviceList", "index")]?.length : $switch_tagName(paramsData["tagName"], paramsData["deviceList"].length, paramsData["index"]?.length, 2)})`,
                                            padding: item === "zoomAxis" ? 0 : "21px 0 43.5px 0"
                                        }}>
                                        {item !== "zoomAxis" && <div className={lessModule["left-group__index"]}>{$switch_index(props.mode ? $switch_mode(props.mode, "device" in sourceData ? "device" : paramsData["index"][0], item) : $switch_tagName(paramsData["tagName"], "device" in sourceData ? "device" : paramsData["index"][0], item, "device" in sourceData ? "device" : paramsData["index"][0]))}</div>}
                                        <div className={lessModule["left-group__chart"]} style={{ marginLeft: item === "zoomAxis" ? 61 : 0 }}>
                                            <HomePage_ChartLineComponent id={`chartListItem${idx}`}
                                                name={`${item}${paramsData["tagName"].includes("双时段") && idx < 2 ? "时段" : ""}`} color={$echartsData["chartLineColorList"][0]} mode={props.mode} isWarningLine={isWarningLine} zoomList={zoomList}
                                                sourceData={{
                                                    time: sourceData[paramsData["tagName"].includes("双时段") && idx ? "bTime" : "time"],
                                                    data: props.mode ? $switch_mode(props.mode, Object.values(sourceData["device" in sourceData ? "device" : paramsData["index"][0]] ?? {})[idx], Object.values(sourceData[item] ?? [])[0]) :
                                                        $switch_tagName(paramsData["tagName"], Object.values(sourceData["device" in sourceData ? "device" : paramsData["index"][0]] ?? {})[idx], Object.values(sourceData[item] ?? [])[0], Object.values(sourceData["device" in sourceData ? "device" : paramsData["index"][0]] ?? {})[idx])
                                                }}
                                                change_zoomList={(item: Array<number>) => setZoomList([...item])} />
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </>
                }
            </div>
            <div className={lessModule["homePageAnalysisComponent-right"]} >
                <div ref={viewDimensionsComponentRef}>
                    <HomePage_AnalysisComponent_ViewDimensionsComponent monitoringType={props.monitoringType} monitorModalName={props.monitorModalName} mode={props.mode} isTag={props.isTag} change_paramsData={change_paramsData} />
                </div>
                {
                    paramsData["tagName"] && $switch_tagName(paramsData["tagName"], paramsData["deviceList"]?.length > 1, paramsData["index"]?.length > 1, true) && <HomePage_AnalysisComponent_CorrelationComponent name={paramsData["tableName"]} sourceOption={$switch_tagName(paramsData["tagName"], paramsData["deviceList"], paramsData["index"], ["时段A", "时段B"])} sourceList={sourceData["correlation"]}/>
                }
                <HomePage_AnalysisComponent_DataStaticComponent mode={props.mode || paramsData["mode"]} tableName={props.tableName || paramsData["tableName"]} tableReferenceHeight={viewDimensionsComponentHeight} monitoringType={props.monitoringType} paramsData={paramsData} sourceData={sourceData} />
            </div>
        </div>
    )
}


export default HomePage_AnalysisComponent